package com.rongxun.hbwallet.ui.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.rongxun.base.MvpFragment;
import com.rongxun.hbwallet.R;
import com.rongxun.hbwallet.constants.HttpConstants;
import com.rongxun.hbwallet.constants.SPKey;
import com.rongxun.hbwallet.jsinterface.JsInteration;
import com.rongxun.hbwallet.model.bean.H5UserInfo;
import com.rongxun.hbwallet.model.bean.ShareContent;
import com.rongxun.hbwallet.model.bean.User;
import com.rongxun.hbwallet.mvp.contract.ICommunity;
import com.rongxun.hbwallet.mvp.presenter.CommunityPresenter;
import com.rongxun.hbwallet.ui.activities.LoginActivity;
import com.rongxun.utils.ActivityUtils;
import com.rongxun.utils.FlyLog;
import com.rongxun.utils.JsonUtils;
import com.rongxun.utils.PreferenceUtils;
import com.rongxun.utils.StatusBarUtil;
import com.rongxun.widget.LoadingDialog;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import wendu.webviewjavascriptbridge.WVJBWebView;

/**
 * 创建者     庄丰泽
 * 创建时间   2018/5/21 10:28
 * 描述  社区
 */

public class CommunityFragment extends MvpFragment<ICommunity.IView, CommunityPresenter> implements ICommunity.IView, View.OnKeyListener {
    @BindView(R.id.shop_wv)
    WVJBWebView mWebView;
    @BindView(R.id.toolbar_title)
    TextView    mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar     mToolbar;
    @BindView(R.id.shop_prb)
    ProgressBar mShopPrb;
    @BindView(R.id.toolbar_right_text)
    TextView    mShare;
    Unbinder unbinder;
    private String url = HttpConstants.WEB_ADDRESS.COMMUNITY_URL;
    private Dialog            loadingDialog;
    private ShareContent      mShareContent;
    private BottomSheetDialog mBottomSheet;


    @Override
    public void showLoading(boolean isShow) {
        if (isShow)
            loadingDialog.show();
        else
            loadingDialog.cancel();
    }

    @Override
    public void showError(String msg, String errorCode) {
    }

    @Override
    public void checkPermissionsSuccessful(String... permissions) {

    }

    @Override
    public void release() {
        if (mWebView != null) {
            mWebView.freeMemory();
            mWebView.clearCache(true);
            mWebView.clearHistory();
            mWebView.clearFormData();
            mWebView.destroy();
        }
        if (loadingDialog != null)
            loadingDialog.cancel();
    }

    @NonNull
    @Override
    public CommunityPresenter createPresenter() {
        return new CommunityPresenter(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_web;
    }

    @Override
    protected void init() {

        StatusBarUtil.setToolBarPaddingTop(mToolbar, activity);
        mToolbarTitle.setText(getString(R.string.community));
        mShare.setText(activity.getString(R.string.share));
        loadingDialog = LoadingDialog.createLoadingDialog(activity, getString(R.string.load), true);
        initWebView();
    }

    private void initWebView() {
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //                if (url.startsWith(HttpConstants.WEB_ADDRESS.COMMUNITY_URL)) {
                //                    ActivityUtils.startActivityWithAnimotion(activity, new Intent(activity, WebActivity.class)
                //                            .putExtra(IntentKey.WEB_URL, url));
                //                    return true;
                //                }


                return false;
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                mShopPrb.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                FlyLog.i("onPageFinished" + url);
                super.onPageFinished(view, url);
                mShopPrb.setVisibility(View.GONE);
                callEvaluateJavascript(mWebView);
                if (url.startsWith(HttpConstants.WEB_ADDRESS.NEWSDETAIL_URL)) {
                    mShare.setVisibility(View.VISIBLE);
                } else {
                    mShare.setVisibility(View.GONE);
                }
            }
        });


        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (title != null) {
                    mToolbarTitle.setText(title);
                }
            }

            //加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                mShopPrb.setProgress(newProgress);

            }


            @Override
            public void onRequestFocus(WebView view) {
                super.onRequestFocus(view);
            }

            @Override
            public void onCloseWindow(WebView window) {
                super.onCloseWindow(window);
            }

            @Override
            public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
                FlyLog.i("onJsBeforeUnload" + url);

                return super.onJsBeforeUnload(view, url, message, result);

            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

        });
        // 得到setting
        WebSettings settings = mWebView.getSettings();

        //支持的语言类型
        settings.setDefaultTextEncodingName("UTF-8");
        //设置可以访问文件
        settings.setAllowFileAccess(true);

        settings.setDomStorageEnabled(true);

        settings.setJavaScriptEnabled(true);//设置JS可用

        mWebView.addJavascriptInterface(new JsInteration(activity), "control");//传递对象进行交互

        settings.setTextZoom(100);
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setLoadWithOverviewMode(true);

        mWebView.setOnKeyListener(this);
    }


    @Override
    protected void onLazyLoadOnce() {
        super.onLazyLoadOnce();
        mWebView.loadUrl(url);
        mWebView.registerHandler("setNativeTitle", (WVJBWebView.WVJBHandler<String, String>) (s, wvjbResponseCallback) ->
                mToolbarTitle.setText(s));

        mWebView.registerHandler("getNativeUserInfo", (WVJBWebView.WVJBHandler<String, String>) (s, wvjbResponseCallback) ->
                wvjbResponseCallback.onResult(getUserInfo()));

        mWebView.registerHandler("tokenExpired", (WVJBWebView.WVJBHandler<String, String>) (s, wvjbResponseCallback) ->
                ActivityUtils.startActivityWithAnimotionBottomToTop(activity, new Intent(activity, LoginActivity.class)));
    }

    private void callEvaluateJavascript(@NonNull WVJBWebView webView) {
        String toJson = getUserInfo();
        mWebView.callHandler("setH5UserInfo", toJson, (WVJBWebView.WVJBResponseCallback<String>) data -> {

        });

    }

    private String getUserInfo() {
        H5UserInfo h5UserInfo = new H5UserInfo();
        //        h5UserInfo.setToken(PreferenceUtils.getString(SPKey.TOKEN,
        //                "eyJhbGciOiJIUzUxMiJ9.eyJjb3VudHJ5Ijoi5Lit5Zu9Iiwic3ViIjoiMTM3OTg0NjQxODIiLCJsYXN0cGFzc3dvcmRyZXNldGRhdGUiOjE1MzQ0ODYxMzEwMDAsImljb24iOm51bGwsIm1vYmlsZSI6IjEzNzk4NDY0MTgyIiwibGFuZ3VhZ2UiOm51bGwsImlkIjoxNSwiZXhwIjoxNTM1OTQ1ODE1LCJpYXQiOjE1MzUzNDEwMTUsImVtYWlsIjpudWxsLCJlbmFibGVkIjp0cnVlLCJ1c2VybmFtZSI6IjEzNzk4NDY0MTgyIn0.6OfQk2J0bfWBiVpiToK8UA8GdLtop2tSCzZYLXKTI7B5o6gnM65aEP7ESYcrodGzTyWlOkZDrcz7LuCOlrLoRQ"));

        h5UserInfo.setToken(PreferenceUtils.getString(SPKey.TOKEN, ""));
        String userJson = PreferenceUtils.getString(SPKey.USER, "");

        User user = JsonUtils.fromJson(userJson, User.class);

        h5UserInfo.setUser(user);

        String toJson = JsonUtils.toJson(h5UserInfo);

        FlyLog.i("toJson" + toJson);
        return toJson;
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        FlyLog.i("mWebView.canGoBack()");
        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mShareContent = null;
            mWebView.goBack();
            return true;
        }
        return false;
    }


    @OnClick(R.id.toolbar_right_text)
    public void onViewClicked() {
        getShareContent();

    }

    private void getShareContent() {

        mWebView.callHandler("shareContent", getUserInfo(), (WVJBWebView.WVJBResponseCallback<String>) data -> {
            mShareContent = JsonUtils.fromJson(data, ShareContent.class);
            FlyLog.i("mShareContent" + mShareContent);
            share();
        });
    }

    private void share() {
        mBottomSheet = new BottomSheetDialog(activity);
        mBottomSheet.setCancelable(true);//设置点击外部是否可以取消
        mBottomSheet.setContentView(R.layout.layout_share);//设置对框框中的布局

        mBottomSheet.findViewById(R.id.share_circle).setOnClickListener(v -> {
            shareToCircle();
        });
        mBottomSheet.findViewById(R.id.share_wechat).setOnClickListener(v -> {
            shareToWeChat();
        });

        mBottomSheet.show();//显示弹窗
    }

    private void shareToCircle() {

    }

    private void shareToWeChat() {

    }
}